package com.txy.threadpool;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.Map;
import java.util.concurrent.*;

public class WatchingThreadPool extends FixedThreadPool implements Runnable {


    private final Map<URL, ThreadPoolExecutor> THREAD_POOLS = new ConcurrentHashMap<>();

    public WatchingThreadPool() {
        //每隔3秒打印线程使用情况
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this, 1, 1, TimeUnit.SECONDS);

    }
    // 通过父类创建线程池


    @Override
    public Executor getExecutor(URL url) {
        final Executor executor = super.getExecutor(url);
        if(executor instanceof ThreadPoolExecutor) {
            THREAD_POOLS.put(url, (ThreadPoolExecutor)executor);
        }
        return executor ;
    }

    @Override
    public void run() {
        // 遍历线程池
        for(Map.Entry<URL, ThreadPoolExecutor> entry : THREAD_POOLS.entrySet()) {
            final URL url = entry.getKey();
            final ThreadPoolExecutor executor = entry.getValue();
            // 开始计算
            final int activeCount = executor.getActiveCount();
            final int poolSize = executor.getCorePoolSize();
            double usePercent = activeCount / (poolSize*1.0) * 100;

            if(usePercent > 90) {
                System.err.println("超出警戒线TP90: host:"+url.getIp()+" 当前使用率是:"+usePercent+" URL:"+url);
            }  else {
                System.out.println("线程池执行状态: ["+activeCount+"/"+poolSize+":"+usePercent+"%]");
            }
        }
    }
}
